package hy.realm;

import hy.beans.Perms;
import hy.beans.Role;
import hy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    public String getName(){
        return "myrealm";
    }
    @Autowired
    UserService service;
    //用户授权处理，判断用户是否拥有某个角色或权限时会自动调用，该方法主要用于前端页面调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {
        String username=(String)p.getPrimaryPrincipal();
        List<Role>roles = service.findRolesByUserName(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        System.out.println("+++++++++++++++++++"+roles+"+++++++++++++++++++");
        roles.forEach(r->{
            if(r==null){
                return;
            }
            info.addRole(r.getName());
            List<Perms> perms=service.findPermsByRoleId(r.getId());
            perms.forEach(perm->{info.addStringPermission(perm.getName());});
        });
        return info;
    }

    //认证过程
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken t) throws AuthenticationException {
        String name = (String)t.getPrincipal();//a1
        String pass = new String((char[])t.getCredentials());//123
        service.login(name,pass);
        return new SimpleAuthenticationInfo(name,pass,getName());
    }
}